<?php
/**
 * Created by PhpStorm.
 * User: SCF
 * Date: 2018/9/26
 * Time: 9:40
 */

namespace App\Services;

use App\Models\User;
use Illuminate\Support\Facades\DB;

class PageService
{

    /**
     * @param $queryObj
     * @param int $page
     * @param int $pageSize
     * @param bool $type
     * @return array
     */
    public static function getPageData($queryObj, $page = 1, $pageSize = 15, $type = false)
    {

        $total = $queryObj->count();
        $data = $queryObj->paginate($pageSize, ['*'], 'page', $page)->items();

        $data = static::format($data);
        //只需要返回数据的type = false
        if (empty($type)) {
            return $data;
        }
        return [
            'pagination' => [
                'page' => (int)$page,
                'size' => (int)$pageSize,
                'total' => (int)$total,
            ],
            'list' => $data
        ];
    }

    /**
     * 格式化返回分页数据
     * @param $data
     * @param $page
     * @param $pageSize
     * @param $total
     * @return array
     */
    public static function formatPageData($data, $page, $pageSize, $total)
    {
        return [
            'pagination' => [
                'page' => (int)$page,
                'size' => (int)$pageSize,
                'total' => (int)$total,
            ],
            'list' => $data
        ];
    }

    /**
     * 格式化list数据
     * @param $data
     * @return array
     */
    public static function format($data)
    {
        $result = [];
        if (is_array($data)) {
            foreach ($data as $key => $val) {
                if (is_object($val)) {
                    $val = json_decode(json_encode($val), true);
                }
                foreach ($val as $ke => $va) {
                    $result[$key][$ke] = is_object($va) ? (array)$va : (is_array($va) ? array_unique($va) : $va);
                }
            }
        }
        return $result;
    }
}
